package com.lyr.query.dynamic.config;

import com.lyr.query.dynamic.core.domain.DynamicQueryProperties;
import com.lyr.query.dynamic.core.handler.MybatisInterceptor;
import com.lyr.query.dynamic.core.schema.SchemaInitializer;
import com.lyr.query.dynamic.core.service.ConfigService;
import javax.servlet.http.HttpServletRequest;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Lazy;

/**
 * 核心配置类
 *
 * @author zk
 */
@ComponentScan("com.lyr.query.dynamic")
@MapperScan("com.lyr.query.dynamic.core.mapper")
@EnableConfigurationProperties(DynamicQueryProperties.class)
public class DynamicQueryAutoConfiguration {

    /**
     * 初始化数据库表结构
     *
     * @param properties         配置信息
     * @param sqlSessionFactory  sqlSessionFactory
     */
    @Bean
    public SchemaInitializer mppSchemaInitializer(DynamicQueryProperties properties, SqlSessionFactory sqlSessionFactory) {
        return new SchemaInitializer(properties, sqlSessionFactory);
    }

    /**
     * 注册条件sql拦截器，其中configService为配置服务，用于获取配置信息，因为循环依赖 sqlSessionFactory -> MybatisInterceptor -> ConfigService -> sqlSessionFactory 所以configService需要使用@Lazy注解，延迟注入
     *
     * @param configService      配置服务
     * @param properties         配置信息
     * @param applicationContext spring环境上下文，用于获取bean
     */
    @Bean
    public Interceptor dynamicSqlInterceptor(@Lazy ConfigService configService, DynamicQueryProperties properties, HttpServletRequest request,
        ApplicationContext applicationContext) {
        return new MybatisInterceptor(configService, properties, request, applicationContext);
    }
}